<?php
namespace app\api\controller;
use think\Controller;
use think\Validate;
use think\Db;
use think\Config;
use app\api\controller\Personal;

class Order extends Controller{

    //我的订单列表
    public function orderList(){
       $user_id = input('post.user_id');
       if(!is_numeric($user_id)){
          return json_encode(array('code'=>401,'msg'=>'user_id类型错误'));
       }
       $order_status = input('post.status');
       if($order_status){
          if(!is_numeric($order_status)){
             return json_encode(array('code'=>401,'msg'=>'status类型有误'));
          }
          if($order_status != 1000){
             $where = "o.order_status = {$order_status}";
          }else{
            $where = 'o.order_status < 5';
          }
       }else{
          $order_status = 0;
          $where = "o.order_status = 0";
       }
       $order_list = db('order')->alias('o')
                                ->field('o.order_id,o.order_sn,o.order_status,o.pay_price as goods_price_sum,o.order_type,o.type,o.preferential_price,o.use_id')
                                ->where($where)
                                ->where("o.user_id = {$user_id}")
                                ->order('o.add_time desc')
                                ->select();
       foreach($order_list as $key=>$value){
          $order_list[$key]['goods'] = db('order_goods')->field('goods_id,spec_item,spec_item_key,goods_number,goods_price,deposit,rent')
                                                        ->where("order_id = {$value['order_id']}")
                                                        ->select();
          foreach($order_list[$key]['goods'] as $k=>$v){
             $goods_info = db('goods')->field('name,thumbnail_img')->where("goods_id = {$v['goods_id']}")->find();
             $order_list[$key]['goods'][$k]['goods_name'] = $goods_info['name'];
             if(!Validate::is($goods_info['thumbnail_img'],'url')){
                 $order_list[$key]['goods'][$k]['thumbnail_img'] = 'http://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$goods_info['thumbnail_img'];
             }
             if($order_list[$key]['type'] == 2){
                unset($order_list[$key]['goods'][$k]['deposit']);
                unset($order_list[$key]['goods'][$k]['rent']);
             }
          }
          $order_list[$key]['goods_number_sum'] = db('order_goods')->where("order_id = {$value['order_id']}")->sum('goods_number');
       }
       if($order_list){
            return json_encode(array('code'=>200,'msg'=>'请求成功','order_list'=>$order_list));
       }else{
            return json_encode(array('code'=>201,'msg'=>'请求失败或暂时还没有订单'));
       }
    }

    //未付款  已付款  已发货 状态下的订单数量统计
    public function orderSum(){
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){
           return json_encode(['code'=>401,'msg'=>'user_id类型错误']);
        }
        $unpaid_order_sum = db('order')->where("user_id = {$user_id} AND order_status = 0")->count();
        $already_order_sum = db('order')->where("user_id = {$user_id} AND order_status = 1")->count();
        $shipped_order_sum = db('order')->where("user_id = {$user_id} AND order_status = 2")->count();
        return json_encode(['code'=>200,'msg'=>'请求成功','unpaid_order_sum'=>$unpaid_order_sum,'already_order_sum'=>$already_order_sum,'shipped_order_sum'=>$shipped_order_sum]);
    }

    //未支付 (重新发起支付)
    public function payAgain(){
       $order_id = input('post.order_id');
       $mode = input('post.mode');
       if(!is_numeric($order_id)){
          return json_encode(['code'=>401,'msg'=>'order_id类型错误']);
       }
       $where = "order_id = {$order_id}";
       $order_info = db('order')->field('user_id,order_status,goods_price,pay_price,order_type,type,postage,deposit_price,preferential_price,use_id')->where($where)->find();
       //共享时需要邮费;购买暂时未定;order_type 1快递;2上门;  type 1共享珠宝;2在售珠宝;
       //共享珠宝订单 且选择快递送货方式;
       if(($order_info['order_type'] == 1) && ($order_info['type'] == 1)){
           $real_postage = db('config')->where("name = 'postage'")->value('value');
           if($real_postage != 0){
               if($order_info['postage'] != $real_postage){
                   return json_encode(['code'=>401,'msg'=>'postage参数被篡改']);
               }
           }
       }
       if($order_info['order_status'] != 0){
          return json_encode(['code'=>401,'msg'=>'订单状态不对']);
       }
       $openid = db('user')->where("user_id = {$order_info['user_id']}")->value('openid');
       $goods = db('order_goods')->field('goods_id,spec_item,goods_number,goods_price,deposit,rent,settlement')->where($where)->select();
       $goods_name = [];
       foreach($goods as $key=>$value){
            $goods_list_name = db('goods')->where("goods_id = {$value['goods_id']}")->value('name');
            $goods_name[] = $goods_list_name.'*'.$value['goods_number'];
            $field = 'store,price,deposit,rent,settlement';
            if($mode == 1){
                $goods_info = db('spec_goods_price')->field($field)->where("goods_id = {$value['goods_id']} AND price_key = {$value['spec_item']}")->find();
            }else{
                $goods_info = db('spec_goods_price')->field($field)->where("goods_id = {$value['goods_id']} AND price_key = 0")->find();
            }
            $goods[$key]['goods_real_price'] = $goods_info['price'];
            if($order_info['type'] == 1){
                $goods[$key]['goods_real_deposit'] = $goods_info['deposit'];
                $goods[$key]['goods_real_rent'] = $goods_info['rent'];
                $goods[$key]['goods_real_settlement'] = $goods_info['settlement'];
            }
       }
       $goods_name = implode(',',$goods_name);
       $price = [];
       $deposit = [];
       foreach($goods as $k=>$v){
              if($goods[$k]['goods_real_price'] != $goods[$k]['goods_price']){
                      return json_encode(array('code'=>401,'msg'=>'goods_price参数被篡改'));
              }
              unset($goods[$k]['goods_real_price']);
              if($order_info['type'] == 1){
                  if($goods[$k]['goods_real_deposit'] != $goods[$k]['deposit']){
                      return json_encode(['code'=>401,'msg'=>'deposit参数被篡改']);
                  }
                  unset($goods[$k]['goods_real_deposit']);
                  if($goods[$k]['goods_real_rent'] != $goods[$k]['rent']){
                      return json_encode(['code'=>401,'msg'=>'rent参数被篡改']);
                  }
                  unset($goods[$k]['goods_real_rent']);
                  if($goods[$k]['goods_real_settlement'] != $goods[$k]['settlement']){
                      return json_encode(['code'=>401,'msg'=>'settlement参数被篡改']);
                  }
                  unset($goods[$k]['goods_real_settlement']);
              }
              $price[] = $goods[$k]['goods_price']*$goods[$k]['goods_number'];
              $deposit[] = $goods[$k]['deposit']*$goods[$k]['goods_number'];
       }
        if($order_info['type'] == 2){
           $goods_name = '购买珠宝（'.$goods_name.'）'; 
           $price_sum = array_sum($price);
           $real_goods_price = $price_sum;
           if($real_goods_price != $order_info['goods_price']){return json_encode(array('code'=>401,'msg'=>'订单总价不对'));}   
        }elseif($order_info['type'] == 1){
           $goods_name = '共享珠宝（'.$goods_name.'）';
           $deposit_sum = array_sum($deposit);  //商品押金总额
           if($order_info['deposit_price'] > $deposit_sum){return json_encode(['code'=>401,'msg'=>'现付押金金额不对']);}//订单支付押金不能超过商品押金总额
           if($order_info['order_type'] == 1){
              $real_goods_price = $order_info['deposit_price'] + $order_info['postage'];
           }else{
              $real_goods_price = $order_info['deposit_price'];
           }
           if($real_goods_price != $order_info['goods_price']){return json_encode(['code'=>401,'msg'=>'订单总价不对']);}
        }   
        $real_pay_price = $real_goods_price - $order_info['preferential_price'];     
        if($real_pay_price != $order_info['pay_price']){return json_encode(['code'=>401,'msg'=>'实际支付金额不符']);}
        if($order_info['type'] == 1){
              $order_sn = 'S'.generateOrderNum();
        }elseif($order_info['type'] == 2){
             $order_sn = 'B'.generateOrderNum();
        }
       if($order_info['pay_price'] > 0){
               Db::startTrans();
               try{
                      $change_order_sn = array('order_sn'=>$order_sn);
                      $update_data = db('order')->where("order_id = {$order_id}")->update($change_order_sn);


                      // 实例支付接口
                      $pay = & load_wechat('Pay');
                      // 获取预支付ID
                      $notify_url = 'https://'.$_SERVER['HTTP_HOST'].'/api/Home/notify';
                      //$order_info['pay_price'] = 0.01;
                      $prepayid = $pay->getPrepayId($openid,$goods_name, $order_sn, $order_info['pay_price'] * 100, $notify_url, $trade_type = "JSAPI");

                      // 创建JSAPI签名参数包
                      $options = $pay->createMchPay($prepayid);
                      Db::commit();
               } catch (\Exception $e){
                      Db::rollback();
                      return json_encode(['code' => 201,'msg' => '订单提交失败']);
               }
               return json_encode(['code' => 200,'msg' => '提交成功','pay' => $options,'order_id' => $order_id]);
        }
    }

    //取消订单 (如果是共享订单,还需要判断有无押金,如果有押金,还需要退还押金)
    public function cancelOrder(){
       $order_id = input('post.order_id');
       if(!is_numeric($order_id)){
          return json_encode(['code'=>401,'msg'=>'order_id类型有误']);
       }
       $where = "order_id = {$order_id}";
       $order_info = db('order')->field('order_status,user_id,type,deposit_price,preferential_price,use_id')->where($where)->find();//type=1共享订单;type=2销售订单
       if($order_info['order_status'] != 0){
          return json_encode(['code'=>401,'msg'=>'订单状态不对']);
       }
       Db::startTrans();
       try{
         if($order_info['use_id']){
               $str = "use_id = {$order_info['use_id']}";
               $coupon_state = db('coupons_use')->where($str)->value('state');
               if($coupon_state == 1){
                  db('coupons_use')->where($str)->update(['state'=>0]);
               }
          }
          $cancel_order = db('order')->where($where)->update(['order_status'=>4]);
          $goods_info = db('order_goods')->field('goods_id,spec_item,goods_number,deposit,code')->where("order_id = {$order_id}")->select();
          $deposit = [];
          foreach($goods_info as $k=>$vo){
              $where = "goods_id = {$vo['goods_id']} AND price_key = {$vo['spec_item']}";
              db('spec_goods_price')->where($where)->setInc('store',$vo['goods_number']);
              $code = '';
              $code = explode(',',$vo['code']);
              foreach($code as $key=>$value){
                 db('code')->where("code_id = {$value}")->update(['state'=>0,'update_time'=>'','sale_type'=>0]);
              }
              $deposit[] = $goods_info[$k]['deposit']*$goods_info[$k]['goods_number'];
              //到货通知;
              // $notice = "goods_id = {$vo['goods_id']} AND state = 2";
              // $userArray = db('shortage_goods')->where($notice)->column('user_id');
              // if($userArray){
              //     $goods_name = db('goods')->where("goods_id = {$vo['goods_id']}")->value('name');
              //     foreach($userArray as $a){
              //         $msg = Config::get('chuanglan.msgSign').'您好,您登记的商品'.$goods_name.'现在有货了';
              //         $data['account'] = Config::get('chuanglan.account');
              //         $data['pswd'] = Config::get('chuanglan.password');
              //         $data['msg'] = urlencode($msg);
              //         $data['mobile'] = db('user')->where("user_id = {$a}")->value('phone');
              //         $data['needstatus'] = 'false';
              //         $data['product'] = '';
              //         $data['extno'] = '';
              //         $personal = new Personal();
              //         $personal->curl_post($data);
              //         db('shortage_goods')->where("goods_id = {$vo['goods_id']} AND state = 2 AND user_id = {$a}")->update(['state'=>0,'content'=>$msg]);
              //     }
              // }
          }
          $deposit_sum = array_sum($deposit);
          if($order_info['type'] == 1){
             //如果总押金大于支付押金,此时需要返还抵押押金;
             if($deposit_sum > $order_info['deposit_price']){
                 $mortgage_deposit = $deposit_sum - $order_info['deposit_price'];//抵押押金
                 $map = "user_id = {$order_info['user_id']}";
                 $user_info = db('user')->field('quota,frozen_integral,available_integral')->where($map)->find();
                 //如果押金总额度 > 0,也就是此时存在京东信用对应的额度时,才会返还冻结押金及可用押金;即当用户解绑时,是不需要返还冻结押金及可用押金;
                 if($user_info['quota'] > 0){
                    $return_frozen_integral = $user_info['frozen_integral'] - $mortgage_deposit;//返还冻结押金
                    
                    // $return_available_integral = $user_info['available_integral'] + $mortgage_deposit;//返还可用押金
                    // 可用额度的计算  可用额度 = （总额度 - 冻结额度）> 0 ?总额度-冻结额度:0;
                    $return_available_integral = ($user_info['quota'] - $return_frozen_integral) > 0 ? ($user_info['quota'] - $return_frozen_integral) :0;
                    db('user')->where($map)->update(['frozen_integral'=>$return_frozen_integral,'available_integral'=>$return_available_integral]);
                 }
             }
          }
          $logData = [];
          $logData['order_id'] = $order_id;
          $logData['u_id'] = $order_info['user_id'];
          $logData['content'] = '用户取消订单';
          $logData['create_time'] = time();
          db('order_log')->insert($logData);
          Db::commit();
       }catch(\Exception $e){
          Db::rollback();
          return json_encode(['code'=>201,'msg'=>'订单取消失败']);
       }
       return json_encode(['code'=>200,'msg'=>'订单取消成功']);
    }

    //订单自提  确认收货
    public function pickUpGoods(){
       $order_id = input('post.order_id');
       if(!is_numeric($order_id)){
          return json_encode(array('code'=>401,'msg'=>'order_id类型有误'));
       }
       $where = "order_id = {$order_id}";
       $order = db('order')->field('user_id,order_status,order_type,type')->where($where)->find();
       if(!$order){
          return json_encode(array('code'=>401,'msg'=>'订单不存在'));
       }
       if($order['order_type'] == 1){
          if($order['order_status'] != 2){
             return json_encode(array('code'=>401,'msg'=>'订单状态不对'));
          }
       }elseif($order['order_type'] == 2){
          if($order['order_status'] != 1){
             return json_encode(array('code'=>401,'msg'=>'订单状态不对'));
          }
       }
       //1会员共享; 2销售订单;
       if($order['type'] == 1){
          $lease_time = date('Y-m-d',time());
          $data = array('order_status'=>10,'confirm_time'=>time(),'lease_time'=>strtotime("$lease_time+1day"));
       }elseif($order['type'] == 2){
          $data = array('order_status'=>3,'confirm_time'=>time(),'end_time'=>time());
       }    
       Db::startTrans();
       try{
           db('order')->where($where)->update($data);
           $logData = [];
           $logData['order_id'] = $order_id;
           $logData['u_id'] = $order['user_id'];
           $logData['content'] = '用户收货确认';
           $logData['create_time'] = time();
           db('order_log')->insert($logData);
           Db::commit();
           return json_encode(array('code'=>200,'msg'=>'提货成功或确认收货'));
       }catch(\Exception $e){
           Db::rollback();
           return json_encode(array('code'=>201,'msg'=>'提货失败或确认收货失败'));
       } 

    }

    //订单详情
    public function orderDetail(){
        $order_id = input('post.order_id');
        if(!is_numeric($order_id)){
            return json_encode(array('code'=>401,'msg'=>'order_id类型有误'));
        }
        $where = "order_id = {$order_id}";
        $order_info = db('order')->field('order_sn,user_id,order_status,store_id,consignee,name,phone,numbers,shipping_id,add_time,pay_time,shipping_time,confirm_time,pay_price,order_type,type,postage,deposit_price,preferential_price,use_id')
                                 ->where($where)
                                 ->find();
        if($order_info['use_id']){
            $coupons_id = db('coupons_use')->where("use_id = {$order_info['use_id']}")->value('coupons_id');
            $coupons_info = db('coupons')->field('coupons_id,name')->where("coupons_id = {$coupons_id}")->find();
            $order_info['coupons_info'] = $coupons_info;
        }
        if($order_info['order_type'] == 1){
            $express_delivery_info = [];
            $express_delivery_info['numbers'] = $order_info['numbers'];
            $express_delivery_info['shipping_id'] = $order_info['shipping_id'];
            $express_delivery_info['shipping_name'] = db('shipping')->where("shipping_id = {$order_info['shipping_id']}")->value('name');
            $order_info['express_delivery_info'] = $express_delivery_info;
        }elseif($order_info['order_type'] == 2){
            $order_info['store_info'] = db('store')->field('name as store_name,address,lat,lng,tel')->where("store_id = {$order_info['store_id']}")->find();
            unset($order_info['shipping_id']);
        }
        unset($order_info['numbers']);
        if($order_info['order_status'] == 0){
           $order_info['status_time'] = date("Y年m月d日",$order_info['add_time']);
        }elseif($order_info['order_status'] == 1){
           $order_info['status_time'] = date("Y年m月d日",$order_info['pay_time']);
        }elseif($order_info['order_status'] == 3){
           $order_info['status_time'] = date("Y年m月d日",$order_info['confirm_time']);
        }
        $order_info['add_time'] = date("Y-m-d H:i",$order_info['add_time']);
        if($order_info['order_status'] != 0){
            $order_info['pay_time'] = date("Y-m-d H:i",$order_info['pay_time']);
        }
        //商家发货时间
        if($order_info['order_type'] == 1){
            if($order_info['shipping_time'] == 0){$order_info['shipping_time'] = '';}
            if($order_info['shipping_time'] != ''){
                $order_info['shipping_time'] = date("Y-m-d H:i",$order_info['shipping_time']);
            }    
        }
        //用户收货时间
        if($order_info['confirm_time'] == 0){$order_info['confirm_time'] = '';}
        if($order_info['confirm_time'] != ''){
            $order_info['confirm_time'] = date("Y-m-d H:i",$order_info['confirm_time']);
        }
        $order_info['store_name'] = db('store')->where("store_id = {$order_info['store_id']}")->value('name');
        $order_info['goods'] = db('order_goods')->field('goods_id,spec_item,spec_item_key,goods_number,goods_price,deposit,rent,settlement')
                                                ->where($where)
                                                ->select();
        $order_info['goods_number_sum'] = db('order_goods')->where($where)->sum('goods_number');
        $deposit = [];
        foreach($order_info['goods'] as $k=>$vo){
            $goods_info = db('goods')->field('name,thumbnail_img,mode')->where("goods_id = {$vo['goods_id']}")->find();
            $order_info['goods'][$k]['goods_name'] = $goods_info['name'];
            $order_info['goods'][$k]['mode'] = $goods_info['mode'];
            if(!Validate::is($goods_info['thumbnail_img'],'url')){
                $order_info['goods'][$k]['thumbnail_img'] = 'http://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$goods_info['thumbnail_img'];
            }else{
                $order_info['goods'][$k]['thumbnail_img'] = $goods_info['thumbnail_img'];
            }
            if($order_info['type'] == 1){
               $deposit[] = $vo['deposit']*$vo['goods_number'];
            }elseif($order_info['type'] == 2){
               unset($order_info['goods'][$k]['deposit']);
               unset($order_info['goods'][$k]['rent']);
               unset($order_info['goods'][$k]['settlement']);
            }
        }
        if($order_info['type'] == 1){
                $sharing_info = [];
                $deposit_sum = array_sum($deposit);
                $sharing_info['deposit_sum'] = $deposit_sum;
                if($deposit_sum != $order_info['deposit_price'] && $deposit_sum > $order_info['deposit_price']){
                   $sharing_info['free_deposit'] = $deposit_sum - $order_info['deposit_price'];
                }else{
                   $sharing_info['free_deposit'] = 0;
                }
                $sharing_info['postage'] = $order_info['postage'];
                unset($order_info['postage']);
                $sharing_info['pay_price'] = $order_info['pay_price'];
                unset($order_info['pay_price']);
                $card_info = db('user_card_log')->field('max(validity_time) as max_validity_time')->where("user_id = {$order_info['user_id']}")->find();
                $sharing_info['validity_time'] = $card_info['max_validity_time'];
                if(time() < strtotime($card_info['max_validity_time'])){
                   $sharing_info['time_left'] = floor((strtotime($card_info['max_validity_time'])-time()+86399)/86400);
                }else{
                   $sharing_info['time_left'] = 0;
                }
                $order_info['sharing_info'] = $sharing_info;
        }
        if($order_info){
            return json_encode(array('code'=>200,'msg'=>'请求成功','order_info'=>$order_info));
        }else{
            return json_encode(array('code'=>201,'msg'=>'请求失败'));
        }
    }

    //物流信息
    public function logistics(){
        $shipping_id = input('post.shipping_id');
        if(!is_numeric($shipping_id)){return json_encode(['code'=>401,'msg'=>'shipping_id参数类型错误']);}
        $com = db('shipping')->where("shipping_id = {$shipping_id}")->value('shipping_code');
        // $com = 'zhongtong';
        $num = input('post.numbers');
        // $num = '633505803544';
        if($num == '' || $num == 'null' || $num == 'undefined'){return json_encode(['code'=>401,'msg'=>'numbers参数缺失']);}
        //参数设置
        $post_data = array();
        $post_data["customer"] = 'BDC2FA363F4A20D813AE2A61F5A03017';
        $key= 'AdXXxhfL3481' ;
        $post_data["param"] = json_encode(['com'=>$com,'num'=>$num]);
        $url='http://poll.kuaidi100.com/poll/query.do';
        $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($post_data["sign"]);
        $o="";
        foreach ($post_data as $k=>$v)
        {
            $o.= "$k=".urlencode($v)."&";   //默认UTF-8编码格式
        }
        $post_data=substr($o,0,-1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $result = curl_exec($ch);
        $data = str_replace("\"",'"',$result );
        $data = json_decode($data,true);
        if(isset($data['data'])){
           foreach($data['data'] as $key=>$value){
              $data['data'][$key]['time'] = date('m-d',strtotime($value['time']));
              $data['data'][$key]['ftime'] = date('H:i',strtotime($value['time']));
           }
        }else{
           $data['data'] = '';
        }
        if(!isset($data['state'])){
           $data['state'] = '';
        }
        return json_encode(['code'=>200,'msg'=>'查询成功','data'=>$data['data'],'state'=>$data['state']]);
    }

}